﻿using ETask.Api.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;


namespace ETask.Api.Data
{
    public class ValidationFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // 检查模型验证是否失败
            if (!context.ModelState.IsValid)
            {
                // 收集错误信息
                var errors = context.ModelState
                    .Where(x => x.Value.Errors.Any())
                    .ToDictionary(
                        key => key.Key,
                        value => value.Value.Errors.Select(e => e.ErrorMessage).ToList()
                    );

                // 返回统一格式的错误响应
                context.Result = new BadRequestObjectResult(ApiResponse.Fail(400,string.Join(",",errors)));
            }
        }

        public void OnActionExecuted(ActionExecutedContext context) { }
    }
}
